package com.foyekoo.project001.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.foyekoo.project001.R;
import com.foyekoo.project001.config.SpUtil;

import java.io.IOException;

/**
 * ${huneng} on 2018/8/9 16:38
 */

public class BackgroundMusicService extends Service{
    private static MediaPlayer mMediaPlayer =null ;
    public static final String ACTION_START = "com.data.BackgroundMusicService.ACTION_START";
    public static final String ACTION_STOP = "com.data.BackgroundMusicService.ACTION_STOP";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init(){
        if(mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.bg_01);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                    mediaPlayer.setLooping(true);
                }
            });
            try {
                mMediaPlayer.stop();
                mMediaPlayer.prepare();
                mMediaPlayer.setLooping(true);
             //   mMediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_START);
        filter.addAction(ACTION_STOP);
        registerReceiver(bgMusicReceiver,filter);
    }

    private BroadcastReceiver bgMusicReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(ACTION_START)&& SpUtil.getInstance().getLocalClient().backGroundMusicIsOpen){
                mMediaPlayer.start();
            } else if (intent.getAction().equals(ACTION_STOP)) {
                mMediaPlayer.pause();
            }
        }
    };
}
